import os
import sys
import logging
import json


EXIT_CODE_PASS_CHECK = 0
EXIT_CODE_FAIL_CHECK = 1


logging.basicConfig(level=logging.INFO)


def run_coverage_check(dt_result):
    logging.info("Start checking coverage...")
    incremental_coverage_threshold = os.getenv("INC_COVERAGE_THRESHOLD") or 80
    total_coverage_threshold = os.getenv("TOTAL_COVERAGE_THRESHOLD") or 0
    check_fail = 0
    logging.info(dt_result)
    with open(dt_result, "r") as fp:
        data = json.load(fp)
        for key in data.keys():
            result = data[key]
            linecoverage = result.get("linecoverage", "")
            incremental_coverage = result.get("incremental_coverage", "")
            if not incremental_coverage:
                check_fail += 1
                logging.error(f"Failed to generate incremental coverage.")
                break

            logging.info(f"Total coverage is {linecoverage}, incremental coverage is {incremental_coverage}")
            if float(incremental_coverage.replace("%", "")) < float(incremental_coverage_threshold):
                check_fail += 1
                logging.error(f"Incremental coverage {incremental_coverage} is less then {incremental_coverage_threshold}%.")
            if float(linecoverage.replace("%", "")) < float(total_coverage_threshold):
                check_fail += 1
                logging.error(f"Total coverage {linecoverage} is less then {total_coverage_threshold}%.")
            break

    if check_fail:
        logging.error("Coverage check FAILED.")
        return EXIT_CODE_FAIL_CHECK
    else:
        logging.info("Finish coverage check.")
        return EXIT_CODE_PASS_CHECK


if __name__ == "__main__":
    args = sys.argv
    sys.exit(run_coverage_check(args[1]))
